<!-- 部门管理 -->
<style lang="less" scoped>
.user {
  margin: 15px;
  .icon-btn {
    font-size: 20px;
    color: #555555;
  }
  .smallForm {
    display: inline-block;
  }
  .mr20 {
    margin-right: 20px;
  }
  .formItem {
    width: 200px;
  }
  .smallArr {
    width: 15%;
    display: inline-block;
  }
}
.width90 {
  width: 95%;
}
.redStar {
  color: red;
  font-size: 22px;
}
@media screen and (max-width: 1601px) {
  .user {
    .mr20 {
      margin-right: 5px;
    }
  }
}
@media screen and (max-width: 1488px) {
  .user {
    .formItem {
      width: 150px;
    }
  }
}
</style>


<template>
  <div class="user">
    <Card :bordered="false">
      <p slot="title"
         class="white">系统管理 > <span class="select-font">职能用户管理</span>
      </p>
      <div>
        <Button type="primary"
                @click="addUser"
                class="mr20">新增职能用户</Button>
        <Button type="error"
                @click="del1"
                class="mr20">删除职能用户</Button>
        <Form :model="formItem"
              class="smallForm">
          <Input v-model="formItem.realname"
                 class="formItem mr20"
                 :maxlength="20"
                 placeholder="请输入职能用户姓名"></Input>
          <Input v-model="formItem.username"
                 class="formItem mr20"
                 :maxlength="20"
                 placeholder="请输入职能用户名"></Input>
          <Input v-model="formItem.mobile"
                 class="formItem mr20"
                 :maxlength="20"
                 placeholder="请输入职能联系电话"></Input>
          <Select clearable
                  v-model="formItem.dep_name"
                  class="formItem mr20"
                  placeholder="请选择职能部门">
            <Option v-for="item in depData"
                    :value="item"
                    :key="item">{{ item }}</Option>
          </Select>
        </Form>
        <Button type="info"
                style="margin-left:25px"
                @click="submitSearch(actionPage,saveType)">搜索</Button>
      </div>
    </Card>
    <div class="center">
      <Table :data="userData"
             :columns="theadArr"
             @on-selection-change="showSelect"
             stripe></Table>
      <Page class="pull-right"
            :total="waterRecordPage.total"
            :current="waterRecordPage.current"
            :page-size="waterRecordPage.pageSize"
            size="small"
            show-total
            @on-change="changePage"></Page>
      <Modal v-model="userModal"
             :mask-closable="false">
        <div slot="header">{{updateTitle}}</div>
        <Form :model="userItem"
              :rules="rules"
              :label-width="100"
              ref="JForm">
          <Form-item label="用户账号"
                     prop="username">
            <Input v-model="userItem.username"
                   :readonly="btnChange"
                   :maxlength="20"
                   @on-blur="checkName"
                   placeholder="请输入账号"></Input>
          </Form-item>
          <Form-item label="用户密码"
                     prop="password"
                     v-if="btnSave">
            <Input v-model="userItem.password"
                   :maxlength="16"
                   type="password"
                   placeholder="请输入密码"></Input>
          </Form-item>
          <Form-item label="再次输入密码"
                     prop="password2"
                     v-if="btnSave">
            <Input v-model="userItem.password2"
                   :maxlength="16"
                   type="password"
                   placeholder="请输入密码"></Input>
          </Form-item>
          <Form-item label="用户名称"
                     prop="realname">
            <Input v-model="userItem.realname"
                   :maxlength="16"
                   placeholder="请输入名称"></Input>
          </Form-item>
          <Form-item label="用户邮箱"
                     prop="email">
            <Input v-model="userItem.email"
                   :maxlength="20"
                   placeholder="请输入邮箱"></Input>
          </Form-item>
          <Form-item label="电话号码"
                     prop="mobile">
            <Input v-model="userItem.mobile"
                   :maxlength="11"
                   placeholder="请输入联系方式"></Input>
          </Form-item>
          <Form-item label="用户角色"
                     prop="rolename">
            <Select v-model="userItem.rolename"
                    @on-change="changeRole"
                    filterable
                    clearable
                    style="width:95%">
              <Option v-for="item in rolenameList"
                      :value="item.rolename"
                      :key="item.rolename">{{ item.rolename }}</Option>
            </Select>

          </Form-item>
          <Form-item label="用户部门"
                     prop="departmentName">
            <Select v-model="userItem.departmentName"
                    filterable
                    clearable
                    style="width:95%">
              <Option v-for="item in departmentNameList"
                      :value="item"
                      :key="item">{{ item }}</Option>
            </Select>

          </Form-item>
          <Form-item label="用户类型"
                     prop="user_type">
            <Select v-model="userItem.user_type"
                    disabled
                    clearable
                    style="width:95%">
              <Option v-for="item in typeList"
                      :value="item.value"
                      :key="item.value">{{ item.title }}</Option>
            </Select>

          </Form-item>
          <Form-item label="在职位置"
                     prop="position">
            <Input v-model="userItem.position"
                   :maxlength="50"
                   placeholder="请输入在职位置"></Input>
          </Form-item>
        </Form>
        <div slot="footer">
          <Button v-if="btnSave"
                  type="primary"
                  @click="ok">保存</Button>
          <Button v-if="btnChange"
                  type="primary"
                  @click="changeUser">修改</Button>
          <Button @click="userModal = false">取消</Button>
        </div>
      </Modal>
      <del-modal title="职能用户"
                 :url="urlUserDel"
                 :delArr="selectData"
                 @del="del"
                 ref="delModal"></del-modal>
      <Modal v-model="comfirmModal"
             width="400">
        <p slot="header"
           style="color:#f60;text-align:center">
          <Icon type="information-circled"></Icon>
          <span>是否确认重置回系统初始密码？</span>
        </p>
        <div style="text-align:center">
          <p>确认重置密码？</p>
        </div>
        <div slot="footer">
          <Button type="error"
                  size="large"
                  long
                  @click="backPassword">重置</Button>
        </div>
      </Modal>
    </div>
  </div>
</template>


<script>
import { ajaxPost } from 'global/axios';
import storage from 'good-storage';
import delModal from 'public/delModal';
import md5 from 'md5';
export default {
  components: {
    'del-modal': delModal,
  },
  data() {
    return {
      urlUserList: '/sys/userinfo/list',
      urlUserNew: '/sys/userinfo/new',
      urlUserEdit: '/sys/userinfo/edit',
      urlUserDel: '/sys/userinfo/del',
      urlRoleList: '/sys/role/list',
      urlDepartmentNameList: '/sys/department/distinct',
      urlAddressList: '/sys/department/getTree',
      urlDepList: '/sys/department/distinct',
      urlPassWord: '/sys/userinfo/pwdreset',
      userData: [],
      comfirmModal: false,
      rules: {
        username: [
          { required: true, message: '用户账号不能为空', trigger: 'blur' },
          {
            pattern: '^((?![A-Z]).)*$',
            message: '请不要使用大写',
            trigger: 'blur',
          },
          { min: 3, max: 15, message: '用户账号请大于3位小于15位' },
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback, source, options) {
              let reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[.~!?@#\-\+\=\_$%^&*])[\da-zA-Z~.!?@#\-\+\=\_$%^&*]{8,16}$/;
              // let complexReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@!%*#?&_])[A-Za-z\d$@$!%*#?&]{8,}$/; // 复杂度校验
              if (value.length < 8) {
                callback(new Error('密码不能少于8位'));
              } else if (value.length > 16) {
                callback(new Error('密码不能大于16位'));
              } else if (!reg.test(value)) {
                callback(new Error('密码中至少包含数字、字母和符号'));
              // } else if (!complexReg.test(value)) {
              //   callback(new Error('你的密码强度太低, 请修改'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
        password2: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback, source, options) {
              let reg = /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[.~!?@#\-\+\=\_$%^&*])[\da-zA-Z~.!?@#\-\+\=\_$%^&*]{8,16}$/;
              // let complexReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@!%*#?&_])[A-Za-z\d$@$!%*#?&]{8,}$/; // 复杂度校验
              if (value.length < 8) {
                callback(new Error('密码不能少于8位'));
              } else if (value.length > 16) {
                callback(new Error('密码不能大于16位'));
              } else if (!reg.test(value)) {
                callback(new Error('密码中至少包含数字、字母和符号'));
              // } else if (!complexReg.test(value)) {
              //   callback(new Error('你的密码强度太低, 请修改'));
              } else {
                callback();
              }
            },
            trigger: 'blur',
          },
        ],
        realname: [
          { required: true, message: '用户姓名不能为空', trigger: 'blur' },
        ],
        mobile: [
          { required: true, message: '用户电话号码不能为空', trigger: 'blur' },
        ],
        rolename: [
          { required: true, message: '用户角色不能为空', trigger: 'change' },
        ],
        departmentName: [
          { required: true, message: '用户部门不能为空', trigger: 'change' },
        ],
        position: [
          { required: true, message: '用户在职位置不能为空', trigger: 'blur' },
        ],
      },
      theadArr: [
        {
          type: 'selection',
          width: 60,
          align: 'center',
        },
        {
          title: '用户名',
          key: 'username',
        },
        {
          title: '真实名称',
          key: 'realname',
        },
        {
          title: '联系电话',
          key: 'mobile',
        },
        {
          title: '电子邮件',
          key: 'email',
        },
        {
          title: '在职位置',
          width: 150,
          key: 'position',
        },
        {
          title: '角色',
          key: 'roleName',
        },
        {
          title: '用户类型',
          render: (h, param) => {
            if (param.row.user_type === '0') {
              return h('div', {}, '村级河长');
            } else if (param.row.user_type === '1') {
              return h('div', {}, '镇级河长');
            } else if (param.row.user_type === '2') {
              return h('div', {}, '区级河长');
            } else if (param.row.user_type === '3') {
              return h('div', {}, '市级河长');
            } else if (param.row.user_type === '4') {
              return h('div', {}, '河长办经办人');
            } else if (param.row.user_type === '5') {
              return h('div', {}, '职能人员');
            } else if (param.row.user_type === '6') {
              return h('div', {}, '河长助理');
            } else if (param.row.user_type === '7') {
              return h('div', {}, '河长办负责人');
            } else {
              return '';
            }
          },
        },
        {
          title: '部门',
          key: 'departmentName',
        },
        {
          title: '用户操作',
          align: 'center',
          render: (h, params) => {
            return h('div', [
              h(
                'Button',
                {
                  props: {
                    type: 'primary',
                    size: 'small',
                  },
                  style: {
                    marginRight: '5px',
                  },
                  on: {
                    click: () => {
                      this.edit(params.row, params.index);
                    },
                  },
                },
                '编辑'
              ),
              // h(
              //   'Button',
              //   {
              //     props: {
              //       type: 'warning',
              //       size: 'small',
              //     },
              //     style: {
              //       marginRight: '5px',
              //     },
              //     on: {
              //       click: () => {
              //         this.saveRow = params.row;
              //         this.comfirmModal = true;
              //       },
              //     },
              //   },
              //   '重置密码'
              // ),
            ]);
          },
        },
      ],
      waterRecordPage: {
        current: 1,
        pageSize: 13,
        total: 0,
      },
      actionPage: '1',
      formItem: {
        realname: '',
        mobile: '',
        username: '',
        dep_name: '',
      },
      userModal: false,
      userItem: {},
      btnSave: false,
      btnChange: false,
      updateTitle: '',
      rolenameList: [],
      departmentNameList: [],
      areaArr: [],
      area: [],
      modal2: false,
      selectData: [],
      addressData: [],
      saveType: '0',
      typeList: [
        {
          title: '村级河长',
          value: '0',
        },
        {
          title: '镇级河长',
          value: '1',
        },
        {
          title: '区级河长',
          value: '2',
        },
        {
          title: '市级河长',
          value: '3',
        },
        {
          title: '河长办经办人',
          value: '4',
        },
        {
          title: '职能人员',
          value: '5',
        },
        {
          title: '河长助理',
          value: '6',
        },
        {
          title: '河长办负责人',
          value: '7',
        },
      ],
      depData: [],
      saveRow: {},
    };
  },
  methods: {
    checkName() {
      let params = {
        data: {
          searchValue: {
            username: this.userItem.username,
          },
        },
        url: this.urlUserList,
        token: storage.session.get('token'),
        success: res => {
          if (parseInt(res.data.result.totalSize) !== 0) {
            this.$Message.warning({
              content: '已被注册',
            });
          } else {
            this.$Message.success({
              content: '可用',
            });
          }
        },
      };
      ajaxPost(params);
    },
    submitSearch(page) {
      let params = {
        data: {
          order: { _id: -1 },
          searchValue: {
            user_type: '5',
          },
          pageSize: this.waterRecordPage.pageSize,
          page,
        },
        url: this.urlUserList,
        token: storage.session.get('token'),
        success: res => {
          this.$Loading.finish();
          this.userData = res.data.result.result;
          for (let i = 0; i < this.userData.length; i++) {
            if (this.userData[i].roles.length > 0) {
              this.userData[i].roleName = this.userData[i].roles[0].rolename;
            }
            if (this.userData[i].departments.length > 0) {
              this.userData[i].departmentName = this.userData[
                i
              ].departments[0].name;
            }
          }
          this.waterRecordPage.total = res.data.result.totalSize;
        },
      };
      if (this.formItem.realname !== '') {
        params.data.searchValue.realname = `${this.formItem.realname}|#|like`;
      }
      if (this.formItem.mobile !== '') {
        params.data.searchValue.mobile = `${this.formItem.mobile}|#|like`;
      }
      if (this.formItem.username !== '') {
        params.data.searchValue.username = `${this.formItem.username}|#|like`;
      }
      if (this.formItem.dep_name !== '') {
        params.data.searchValue[
          'departments.name'
        ] = `${this.formItem.dep_name}|#|like`;
      }
      ajaxPost(params);
    },
    changePage(page) {
      this.submitSearch(page);
      this.actionPage = page;
    },
    addUser() {
      this.$refs.JForm.resetFields();
      this.userModal = true;
      this.updateTitle = '新增用户';
      this.btnChange = false;
      this.btnSave = true;
      this.userItem = {
        username: '',
        password: '',
        realname: '',
        email: '',
        mobile: '',
        position: '',
        rolename: '',
        departmentName: '',
        user_type: '',
        password2: '',
      };
    },
    getRoleNameList() {
      let that = this;
      let params = {};
      params.data = {};
      params.data.searchValue = {
        user_type: '5',
      };
      params.token = storage.session.get('token');
      params.url = this.urlRoleList;
      params.success = function (res) {
        that.$Loading.finish();
        that.rolenameList = res.data.result.result;
      };
      ajaxPost(params);
    },
    getDepartmentNameList() {
      let params = {
        data: {
          searchValue: {
            type: '1',
          },
        },
        url: this.urlDepartmentNameList,
        token: storage.session.get('token'),
        success: res => {
          this.departmentNameList = res.data.result;
        },
      };
      ajaxPost(params);
    },
    ok() {
      let that = this;
      let params = {};
      params.data = {};
      if (this.userItem.username != '') {
        params.data.username = this.userItem.username;
      } else {
        this.$Notice.warning({
          title: '请填写账号',
        });
        return;
      }
      if (this.userItem.password != '') {
        let reg = /^(?=.*[A-Za-z])(?=.*\d)/;
        let complexReg = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[$@!%*#?&_])[A-Za-z\d$@$!%*#?&]{8,}$/; // 复杂度校验
        let right = this.userItem.password.match(reg);
        if (right === null) {
          this.$Notice.warning({
            desc: '密码中必须包含大写字母、小写字母、数字两两组合',
          });
          return;
        } else {
          params.data.password = md5(this.userItem.password);
        }
        if(!complexReg.test(this.userItem.password)){
          this.$Notice.warning({
            desc: '你的密码强度太低, 请修改',
          });
          return;
        }
      } else {
        this.$Notice.warning({
          title: '请填写密码',
        });
        return;
      }
      if (this.userItem.password !== this.userItem.password2) {
        this.$Notice.warning({
          title: '两次密码不一致，请重新填写',
        });
        return;
      }
      if (this.userItem.realname != '') {
        params.data.realname = this.userItem.realname;
      } else {
        this.$Notice.warning({
          title: '请填写真实名称',
        });
        return;
      }
      if (this.userItem.mobile != '') {
        params.data.mobile = this.userItem.mobile;
      } else {
        this.$Notice.warning({
          title: '请填写电话',
        });
        return;
      }
      if (this.userItem.rolename != '') {
        for (let i = 0; i < this.rolenameList.length; i++) {
          if (this.rolenameList[i].rolename === this.userItem.rolename) {
            params.data.roles = [];
            params.data.roles[0] = {};
            params.data.roles[0].roleid = this.rolenameList[i].roleid;
            params.data.roles[0].rolename = this.userItem.rolename;
            params.data.roles[0].system_id = this.rolenameList[i].system_id;
          }
        }
      } else {
        this.$Notice.warning({
          title: '请选择角色',
        });
        return;
      }
      if (this.userItem.departmentName !== '') {
        params.data.dep_name = this.userItem.departmentName;
      } else {
        this.$Notice.warning({
          title: '请选择部门',
        });
        return;
      }
      if (this.userItem.user_type != '') {
        params.data.user_type = this.userItem.user_type;
      } else {
        this.$Notice.warning({
          title: '请选择用户类型',
        });
        return;
      }
      if (this.userItem.position != '') {
        params.data.position = this.userItem.position;
      } else {
        this.$Notice.warning({
          title: '请输入在职位置',
        });
        return;
      }
      params.data.email = this.userItem.email;
      params.url = this.urlUserNew;
      params.token = storage.session.get('token');
      params.success = function (res) {
        if (res.data.code == '0000') {
          that.$Loading.finish();
          that.$Message.success({
            content: '新增成功',
          });
          that.userModal = false;
          that.submitSearch(that.actionPage);
        } else {
          that.$Message.warning({
            content: res.data.message,
          });
        }
      };
      ajaxPost(params);
    },
    changeUser() {
      let params = {
        data: {
          username: this.userItem.username,
          password: this.userItem.password,
          realname: this.userItem.realname,
          mobile: this.userItem.mobile,
          email: this.userItem.email,
          user_type: this.userItem.user_type,
          _id: this.userItem._id,
          position: this.userItem.position
        },
        token: storage.session.get('token'),
        url: this.urlUserEdit,
        success: res => {
          if (res.data.code == '0000') {
            this.$Loading.finish();
            this.$Message.success({
              content: res.data.message,
            });
            this.userModal = false;
            this.submitSearch(this.actionPage);
          } else {
            this.$Message.warning({
              content: res.data.message,
            });
          }
        },
      };
      if (this.userItem.rolename != '') {
        for (let i = 0; i < this.rolenameList.length; i++) {
          if (this.rolenameList[i].rolename === this.userItem.rolename) {
            params.data.roles = [];
            params.data.roles[0] = {};
            params.data.roles[0].roleid = this.rolenameList[i].roleid;
            params.data.roles[0].rolename = this.userItem.rolename;
            params.data.roles[0].system_id = this.rolenameList[i].system_id;
          }
        }
      } else {
        this.$Notice.warning({
          title: '请选择角色',
        });
        return;
      }
      if (this.userItem.departmentName !== '') {
        params.data.dep_name = this.userItem.departmentName;
      } else {
        this.$Notice.warning({
          title: '请选择部门',
        });
        return;
      }
      ajaxPost(params);
    },
    showAddress(data) {
      this.addressData = data;
    },
    del1() {
      if (this.selectData.length > 0) {
        this.$refs.delModal.showModal();
      } else {
        this.$Message.warning('请选择用户');
      }
    },
    del() {
      this.selectData = [];
      this.submitSearch(this.actionPage);
    },
    showSelect(data) {
      this.selectData = data; // 把勾选的数组存起来
    },
    edit(row) {
      let that = this;
      this.updateTitle = '编辑用户';
      this.userModal = true;
      this.btnChange = true;
      this.btnSave = false;
      this.userItem = {
        username: row.username,
        password: row.password,
        realname: row.realname,
        email: row.email,
        mobile: row.mobile,
        position: row.position,
        rolename: row.rolename,
        departmentName: row.departmentName,
        user_type: row.user_type,
        _id: row._id,
      };
      this.userItem.rolename = row.roles[0].rolename;
    },
    getDep() {
      let params = {
        data: {
          searchValue: {
            type: '1',
          },
        },
        url: this.urlDepList,
        token: storage.session.get('token'),
        success: res => {
          this.depData = res.data.result;
        },
      };
      ajaxPost(params);
    },
    changeRole(data) {
      this.rolenameList.map(item => {
        if (data == item.rolename) {
          this.userItem.user_type = item.user_type;
        }
      });
    },
    backPassword() {
      let params = {
        data: {
          _id: this.saveRow._id,
        },
        url: this.urlPassWord,
        token: storage.session.get('token'),
        success: res => {
          if (res.data.code == '0000') {
            this.$Loading.finish();
            this.$Message.success({
              content: '重置成功',
            });
            this.comfirmModal = false;
            this.submitSearch(this.actionPage, this.saveType);
          } else {
            this.$Message.warning({
              content: res.data.message,
            });
          }
        },
      };
      ajaxPost(params);
    },
  },
  mounted() {
    this.submitSearch(1);
    this.getRoleNameList();
    this.getDepartmentNameList();
    this.getDep();
  },
};
</script>
